<template>
  <!--  委外-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="产品">
          <el-select
              v-model="searchParam.productId"
              placeholder="请选择选择产品"
              filterable
              clearable
              style="width: 250px"
              @change="productChange"
          >
            <el-option
                v-for="(item, index) of productList"
                :key="index"
                :label="item.productName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="追溯码">
          <el-select
              v-model="searchParam.traceCodeId"
              placeholder="请选择追溯码"
              filterable
              remote
              clearable
              style="width: 300px"
              :remote-method="remoteTraceCodeSearch"
              :loading="traceCodeLoading"
              @change="getList"
          >
            <el-option
                v-for="(item, index) of traceabList"
                :key="index"
                :label="item.traceCode"
                :value="item.id"
            >
              <span style="float: left">{{ item.traceCode }}</span>
              <span style="float: right;color:#777">{{ item.batchNo }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableContent">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="原材料" name="material">
            <MaterialComponent :productId="searchParam.productId"
                               :preorderTraceCodeList="preorderTraceCodeList"></MaterialComponent>
          </el-tab-pane>
          <el-tab-pane label="生产过程" name="production">
            <ProductionComponent :productId="searchParam.productId"
                                 :preorderTraceCodeList="preorderTraceCodeList"></ProductionComponent>
          </el-tab-pane>
          <el-tab-pane label="委外情况" name="outsourcing">
            <OutsourcingComponent :productId="searchParam.productId"
                                  :preorderTraceCodeList="preorderTraceCodeList"></OutsourcingComponent>
          </el-tab-pane>
          <el-tab-pane label="成品发料" name="finishedProduct">
            <FinishedProductComponent :productId="searchParam.productId"
                                      :preorderTraceCodeList="preorderTraceCodeList"></FinishedProductComponent>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import MaterialComponent from '../qualityReport/traceabilityReportComponent/MaterialComponent.vue';
import ProductionComponent from '../qualityReport/traceabilityReportComponent/ProductionComponent.vue';
import OutsourcingComponent from '../qualityReport/traceabilityReportComponent/OutsourcingComponent.vue';
import FinishedProductComponent from '../qualityReport/traceabilityReportComponent/FinishedProductComponent.vue';

const activeTab = ref('material');
const traceCodeLoading = ref(false);
const traceabList = ref([]);
const productList = ref([]);
const searchParam = reactive({
  productId: null,
  traceCodeId: null
});
const preorderTraceCodeList = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 100,
  total: 0
});

const handleTabClick = (tab) => {
  console.log(`当前激活的标签页是：${tab.props.name}`);
};

onMounted(() => {
  getOptions();
});

const getOptions = () => {
  axiosInstance.post('/api/basedataProduct/getAll', {})
      .then(res => {
        productList.value = res.data;
      });
};

const productChange = (productId) => {
  // 重置追溯码选择
  searchParam.traceCodeId = null;
  traceabList.value = [];

  if (!productId) return;

  const product = productList.value.find(item => item.id === productId);
  if (!product) return;

  remoteTraceCodeSearch()
  // 这里不需要立即加载追溯码列表，等待用户输入搜索
};

const remoteTraceCodeSearch = (query) => {
  if (!searchParam.productId) {
    traceabList.value = [];
    return;
  }

  traceCodeLoading.value = true;
  const materialId = productList.value.find(item => item.id === searchParam.productId)?.materialId;

  axiosInstance.post('/api/traceCode/query', {
    materialId,
    productId: searchParam.productId,
    traceCode: query, // 搜索关键词
    current: pagination.current,
    pageSize: pagination.pageSize
  })
      .then(res => {
        if (res.code === 200) {
          traceabList.value = res.data.records;
          pagination.total = res.data.total;
        } else {
          ElMessage.error(res.message);
        }
      })
      .catch(error => {
        console.error('Error fetching trace codes:', error);
        ElMessage.error('获取追溯码列表失败');
      })
      .finally(() => {
        traceCodeLoading.value = false;
      });
};

const getList = (traceCodeId) => {
  if (!traceCodeId) {
    preorderTraceCodeList.value = [];
    return;
  }

  const traceCode = traceabList.value.find(item => item.id === traceCodeId)?.traceCode;
  if (!traceCode) return;

  axiosInstance.post('/api/traceCode/findPreTraceCodeList', {traceCode, id: traceCodeId})
      .then(res => {
        if (res.code === 200) {
          preorderTraceCodeList.value = res.data;
        } else {
          ElMessage.error(res.message);
        }
      })
      .catch(error => {
        console.error('Error fetching pre trace code list:', error);
        ElMessage.error('获取预追溯码列表失败');
      });
};
</script>

<style scoped>
</style>